#!/usr/bin/env python3

import argparse
import pendulum
from glob import glob
from collections import OrderedDict
import re
import os
from pprint import pprint
from shutil import copyfile

def parse_time(string):
	match = re.match(r'(\d{4}\d{2}\d{2}\d{2})(\d{2})?', string)
	if match.group(2):
		return pendulum.from_format(string, 'YYYYMMDDHHmm')
	else:
		return pendulum.from_format(string, 'YYYYMMDDHH')

parser = argparse.ArgumentParser(description='Write namelist for EFSO run.')
parser.add_argument('--time', help='Forecast start time (YYYYMMDDHH)', type=parse_time)
parser.add_argument('--profiler-root', default='/data/raw/profiler')
args = parser.parse_args()


station_dir = os.listdir('{}/{}/{}/{}'.format(args.profiler_root,args.time.format('YYYY'),args.time.format('MM'),args.time.format('DD')))
conver_file = []
file_list   = []
for i in station_dir:
    file_list += glob('{}/{}/{}/{}/{}/ROBS/QI/Z_RADA*'.format(args.profiler_root,args.time.format('YYYY'),args.time.format('MM'),args.time.format('DD'), i))

for pro_file in file_list:
    time = pendulum.from_format(re.findall(r'\d{14}', os.path.basename(pro_file))[0], 'YYYYMMDDHHmmss')
    if time == args.time:
        pro_file_new = '/opt' + pro_file.replace('profiler','profiler-unix')
        if not os.path.exists(os.path.dirname(pro_file_new)):
            os.makedirs(os.path.dirname(pro_file_new))
        copyfile(pro_file,pro_file_new)
        os.system(f'dos2unix "{pro_file_new}"')
